package tw.twandroidproj.app.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.async.future.Future;

import tw.twandroidproj.app.R;
import tw.twandroidproj.app.model.Auth;
import tw.twandroidproj.app.model.ErrorModel;
import tw.twandroidproj.app.model.User;
import tw.twandroidproj.app.network.AuthManager;
import tw.twandroidproj.app.network.OnResponseListener;


public class LoginActivity extends ActionBarActivity
    implements View.OnClickListener{

    private EditText username, password;
    private Button loginButton, signupButton,signupButton2;
    private ProgressBar progressBar;
    private  AuthManager LoginAuth;
    private TextView textView1, textView2, textView3, textView4, textView5;
    /**
     * 本地验证后的username和password
     */
    private String availableUsername,availablePassword;

    /**
     * 登录请求的Future ，主要在取消登录时使用
     */
    private Future<User> userFuture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_tab);

        TabHost m = (TabHost)findViewById(R.id.tabhost);
        m.setup();

        LayoutInflater i=LayoutInflater.from(this);
        i.inflate(R.layout.activity_login, m.getTabContentView());
        i.inflate(R.layout.activity_login2, m.getTabContentView());//动态载入XML，而不需要Activity

        m.addTab(m.newTabSpec("tab1").setIndicator("个人用户").setContent(R.id.loginlayout1));
        m.addTab(m.newTabSpec("tab2").setIndicator("企业用户").setContent(R.id.loginlayout2));
        initView();
        textView1= (TextView)findViewById(R.id.login_name);
    }

    private void initView() {
        username = (EditText) findViewById(R.id.login_username);
        password = (EditText) findViewById(R.id.login_password);
        loginButton = (Button) findViewById(R.id.btn_login);
        loginButton.setOnClickListener(this);
        signupButton = (Button) findViewById(R.id.btn_signup);
        signupButton.setOnClickListener(this);
        signupButton2 = (Button) findViewById(R.id.btn_signup2);
        signupButton2.setOnClickListener(this);
        progressBar = (ProgressBar) findViewById(R.id.login_progress);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 两个按钮的点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                if(!checkUsernameAndPassword()){
                    Toast.makeText(this, "用户名或密码格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }
//                userFuture = Ion.with(this).load(NetParams.LOGIN_URL)
//                        .setBodyParameter("username",availableUsername)
//                        .setBodyParameter("password",availablePassword)
//                        .as(User.class).setCallback(this);
                showProgress();
                 LoginAuth = AuthManager.getInstance(this);
                MyListener myListener =new MyListener();

                LoginAuth.auth(availableUsername, availablePassword, myListener);



                break;

            case R.id.btn_signup:
                Intent intent = new Intent(this, SignupActivity.class);
                startActivity(intent);
                break;

            case R.id.btn_signup2:
                Intent intent2 = new Intent();
                intent2.setClass(LoginActivity.this, SignupActivity2.class);
                LoginActivity.this.startActivity(intent2);
                break;
        }
    }

    /**
     * 本地验证输入的用户名和密码是否合法
     * @return
     */
    private boolean checkUsernameAndPassword() {
        if(username.getText() != null && !username.getText().toString().isEmpty()
                && password.getText() != null && !password.getText().toString().isEmpty()){
            availableUsername = username.getText().toString();
            availablePassword = password.getText().toString();
            return true;
        }else {
            return false;
        }
    }

    /**
     * activity不可见时调用
     */
    @Override
    protected void onStop() {
        super.onStop();
        //取消登录请求
        if(userFuture != null){
            userFuture.cancel();
            showLoginBtn();
        }
    }

    /**
     * 登录失败时显示登录按钮，可以再次登录
     */
    private void showLoginBtn(){
        loginButton.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.INVISIBLE);
    }

    /**
     * 按下登录后显示进度圈等待
     */
    private void showProgress(){
        loginButton.setVisibility(View.INVISIBLE);
        progressBar.setVisibility(View.VISIBLE);
    }

   /* /**
     * 登录请求的回调函数
     * @param e 抛出的异常，如果请求成功则为null
     * @param user 请求成功时返回的User对象, 注意可能为null
     */
  /*  @Override
  /* public void onCompleted(Exception e, User user) {
        //完成登录或失败
        if(user != null && availableUsername.equals(user.getEmail())) {
            Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
//            ((MyApp)getApplication()).setLoginUser(user);
            setResult(ActivityParams.LOGIN_SUCCESS);
            finish();
        }else {
            Toast.makeText(this, "登录失败!\n"+e,Toast.LENGTH_SHORT).show();
            Log.e("Test", "" + e);
            showLoginBtn();
        }
    }*/
   public class MyListener  implements OnResponseListener<Auth>{

       @Override
       public void onSuccess(Auth result) {

        finish();

       }

       @Override
       public void onFailed(ErrorModel errorModel) {

       }
   }

}
